package net.lab1024.sa.admin.module.users.approval.listener;

import com.alibaba.excel.converters.ReadConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.util.NumberUtils;
import com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
@Slf4j
public class CustomTimestampConverter implements Converter<Timestamp> {
    @Override
    public Timestamp convertToJavaData(ReadConverterContext<?> context) throws Exception {
        ReadCellData<?> cellData = context.getReadCellData();

        if (cellData.getType() == CellDataTypeEnum.NUMBER) {
            // Excel numeric date
            BigDecimal numberValue = cellData.getNumberValue();
            long excelEpoch = (numberValue.longValue() - 25569) * 86400 * 1000L; // Adjust for Excel epoch (subtract 25569 days)
            return new Timestamp(excelEpoch);
        } else if (cellData.getType() == CellDataTypeEnum.STRING) {
            // String date with possible different formats
            String cellValue = cellData.getStringValue();
            if (StringUtils.isEmpty(cellValue)) {
                return null;
            }
            SimpleDateFormat sdf;
            if (cellValue.contains("/")) {
                sdf = new SimpleDateFormat("yyyy/M/d");
            } else {
                sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            }
            return new Timestamp(sdf.parse(cellValue).getTime());
        }
        return null;


    }



    @Override
    public Class<?> supportJavaTypeKey() {
        return Timestamp.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return null;
    }


}
